import json
from bs4 import BeautifulSoup
import time


def search_item(html):#解析器
    result = []
    soup = BeautifulSoup(html, "lxml")    #把当前html字符串转成对象，选择“lxml"解析器
    li_ele_arry = soup.select("ul[class ^='gl-warp'] li[class='gl-item']")
    for li_ele in li_ele_arry: #获取对象中的元素（后面还需要解析才能存到数据库中）
        try:
            img = li_ele.select(".p-img")#返回的是列表
            price = li_ele.select(".p-price")
            name = li_ele.select("div[class^='p-name']")
            shop = li_ele.select(".p-shop")
            icons = li_ele.select(".p-icons")#本身是列表结构   [自营, 放心购]

            result.append([
                img[0].a.img.attrs["data-lazy-img"] if img else "",
                price[0].strong.i.text.strip() if price else "",
                name[0].a.text.strip() if name else "",
                shop[0].span.a.attrs["title"].strip() if shop else"",
                json.dumps([x.text.strip() for x in icons[0].select("i[class^='goods-icons']")]),
                time.strftime("%Y-%m-%d")
            ])
        except Exception as e:
            print(e.args)
    return result
